//Component Object
Component({
  options: {
    pureDataPattern: /^_/ // 指定所有 _ 开头的数据字段为纯数据字段
  },
  pageLifetimes:{
    hide:function(){
      let that = this as any
      that.pauseThisAudio()
    }
  },
  properties: {

    audioUrl:{
      type:String,
      value:'',
      
    },
    playingAudioUrl:{
      type:String,
      value:'',
      observer: function(newValue:string){
        let that = this as any
        
        if(newValue !== that.data.audioUrl){
          that.pauseThisAudio()
        }
    
      }
    }
  },
  data: {
    playStatus:'pause',
    _audioContext:null
  },
  methods: {
    changePlayStstus(status:string){
      let that = this as any
      console.log('changePlayStstus that:',that,status)
      that.setData({
        playStatus:status
      },()=>{
        console.log('that:',that.data.playStatus)
      })
    },
    initAudioContext(){
      let that = this as any
      let _audioContext = wx.createInnerAudioContext({
        useWebAudioImplement: true 
      }) as any
      _audioContext.onPlay(()=>{
        // console.log('onCanplay that：',that)
        // console.log('audioContext2:',audioContext)
        that.setData({
          playStatus:'play'
        })
      })
   
      _audioContext.onStop(()=>{
        console.log('stop')
        that.setData({
          playStatus:'pause'
        })
      })
      _audioContext.onEnded(()=>{
        console.log('onEnded')
        that.setData({
          playStatus:'pause'
        })
        
      })
      _audioContext.onWaiting(()=>{
        console.log('onWaiting')
        that.setData({
          playStatus:'play'
        })
      })
      _audioContext.onError((err:any)=>{
        _audioContext.stop()
        console.log('播放错误：',err)
        wx.showToast({
          title:'播放错误',
          duration:3000
        })
        that.setData({
          playStatus:'pause',
          _audioContext: null
        })
        
      })
      that.setData({
        _audioContext
      })
    },
    playThisAudio(){
      let that = this as any
      if(!that.data._audioContext){
        that.initAudioContext()
      }
      that.setData({
        playStatus:'play'
      })
      that.data._audioContext.src = that.data.audioUrl
      that.data._audioContext.play()
      that.triggerEvent('parentPlayThisAudio',{audioUrl: that.data.audioUrl})
      
    },
    pauseThisAudio(){
      let that = this as any
      // console.log('pauseThisAudio ',that.data.audioId)
      if(that.data._audioContext){
        that.data._audioContext.src = ''
        that.data._audioContext.stop()
      }
      (this as any).setData({
        playStatus:'pause'
      })
    }
  },

  attached:function(){
    this.initAudioContext()
  },
  detached:function(){
    let that = this  as any
    if(that.data._audioContext){
      that.pauseThisAudio()
      that.data._audioContext.destroy()
      that.data._audioContext = null
    }

  }
});